<template>
  <div class="app-container">
    <div class="background">
      <el-row :gutter="20">
        <el-col :span="8">
          <div class="grid-content bg-purple">
            <div class="detail">
              <i class="el-icon-document-remove" />
              营收/实收
              <div class="text">
                ￥<span style="color:#ff9900">{{ balance.earns }}</span>
                <span style="color:#19be6b">/{{ balance.actualEarns }}</span>
              </div>
            </div>
          </div>
        </el-col>
      </el-row>
    </div>

    <div style="padding-top:10px;">
      营业天
      <span style="margin-right: .5em">
        <el-date-picker
          v-model="search.date"
          type="daterange"
          placeholder="日期"
          size="medium"
          :editable="false"
          :clearable="false"
          value-format="yyyy/MM/dd"
          @change="filterGenerate();"
        />
      </span>
      <!-- <span style="margin-right: .5em">
        <el-select v-model="search.squad" style="width: 150px;" clearable placeholder="小队" @change="showStaffs()">
          <el-option v-for="item in squads" :key="item.id" :label="item.name" :value="item.id" />
        </el-select>
      </span> -->
      <span style="margin-right: .5em">
        <el-popconfirm title="确定结算剩余订单？" @onConfirm="settleAll()">
          <el-button slot="reference" type="success" plain>批量结算</el-button>
        </el-popconfirm>
      </span>
      <span style="margin-right: .5em">
        <el-popconfirm title="确定反结算今日订单？" @onConfirm="unSettle()">
          <el-button slot="reference" type="danger" plain>反结算</el-button>
        </el-popconfirm>
      </span>
      <span style="margin-right: .5em">
        <el-button slot="reference" type="warning" plain @click="printTable()">打印</el-button>
      </span>
    </div>

    <el-row>
      <div id="print" :key="printRefresh">
        <div v-if="list.length > 0">
          <el-tabs v-model="activeName">
            <el-tab-pane v-for="(item,index) in list" :key="index" :label="item.name" :name="item.type">
              <div v-if="item.type == 'product'">
                <el-table
                  v-loading="loading"
                  :data="statistics[item.type]"
                  element-loading-text="加载中..."
                  fit
                  lazy
                  stripe
                  show-summary
                  highlight-current-row
                  style="width: 100%"
                >
                  <el-table-column label="#" type="index" width="60" />
                  <el-table-column prop="productName" label="产品" width="200" />
                  <el-table-column prop="quantity" label="数量" width="200" />
                  <el-table-column prop="totalPrice" label="总金额" width="200" />
                </el-table>
              </div>
              <div v-else-if="item.type == 'counter'">
                <el-table
                  v-loading="loading"
                  :data="statistics[item.type]"
                  element-loading-text="加载中..."
                  fit
                  lazy
                  stripe
                  show-summary
                  highlight-current-row
                  style="width: 100%"
                >
                  <el-table-column label="#" type="index" width="60" />
                  <el-table-column prop="name" label="台号" width="200" />
                  <!-- <el-table-column prop="quantity" label="数量" width="200" /> -->
                  <el-table-column prop="amount" label="总金额" width="200" />
                </el-table>
              </div>
              <div v-else>
                <el-table
                  v-loading="loading"
                  :data="statistics[item.type]"
                  element-loading-text="加载中..."
                  fit
                  lazy
                  stripe
                  show-summary
                  highlight-current-row
                  style="width: 100%"
                >
                  <el-table-column label="#" type="index" width="60" />
                  <el-table-column prop="name" label="内容" width="200" />
                  <el-table-column prop="products" label="产品" width="420">
                    <template slot-scope="scope">
                      <el-table
                        :data="scope.row.products"
                      >
                        <el-table-column
                          prop="productName"
                          label="产品"
                          width="250"
                        />
                        <el-table-column
                          prop="quantity"
                          label="数量"
                          width="50"
                        />
                        <el-table-column
                          prop="price"
                          label="金额"
                          width="100"
                        />
                      </el-table>
                    </template>
                  </el-table-column>
                  <el-table-column prop="totalAmount" label="总金额" width="200" />
                </el-table>
              </div>
            </el-tab-pane>
          </el-tabs>
        </div>
        <div v-else>
          <div style="color:#ff9900;text-align: center;padding-top:20vh">暂无营业数据</div>
        </div>
      </div>
    </el-row>

    <!-- 销售明细内容 -->
    <el-dialog
      :title="productDialog.title"
      :visible.sync="productDialog.visible"
      width="60%"
    >
      <div>
        <el-table
          :key="productDialog.componentRefresh"
          v-loading="productDialog.loading"
          :data="productDialog.items"
          fit
          lazy
          stripe
          highlight-current-row
          border
          style="width: 100%"
        >
          <el-table-column fixed prop="order.__metadata.counter.__toString" label="台号" />
          <el-table-column fixed prop="specification.__toString" label="产品" />
          <el-table-column fixed prop="quantity" label="数量" />
          <el-table-column fixed prop="quantity" label="结账状态">
            <template slot-scope="scope">
              <el-tag v-if="scope.row.order.__metadata.laterPay == 0" type="success">已结账</el-tag>
              <el-tag v-else type="info">待结账</el-tag>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="productDialog.visible = false">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import print from 'print-js'

export default {
  data() {
    return {
      loading: false,
      activeName: '',
      counters: [],
      products: [],
      staffProductStatistics: [],
      showStaffProductStatistics: [],
      search: {
        date: [],
        squad: null
      },
      balance: {
        earns: 0,
        actualEarns: 0
      },
      // 跨日判断
      checkDate: '08:00',
      productDialog: {
        title: '',
        componentRefresh: 0,
        visible: false,
        loading: false,
        items: []
      },
      printRefresh: 0,
      storeStatistics: null,
      staffs: [],
      squads: [],
      statistics: [],
      list: []
    }
  },
  created() {
    let date = new Date()
    const str = date.toTimeString().substring(0, 5)
    if (str <= this.checkDate) {
      date = new Date(date.getTime() - 86400000)
    }
    const startDate = `${date.getFullYear()}/${date.getMonth() + 1}/${date.getDate()}`
    this.search.date.push(startDate)
    this.search.date.push(startDate)
    this.filterGenerate()
  },
  methods: {
    getStatistics() {
      const nextDate = new Date(new Date(this.search.date[1]).getTime() + 86400000)
      const endDate = `${nextDate.getFullYear()}/${nextDate.getMonth() + 1}/${nextDate.getDate()}`
      this.axios.get(`/officer/orders`, { params: {
        '@filter': `entity.getStatus() >=2 && entity.getCreatedTime() >= datetime.get('${this.search.date[0]} 08:00:00') && entity.getCreatedTime() <= datetime.get('${endDate} 07:59:59')`,
        '@select': `SUM(entity.totalPrice) as amount,entity.laterPay as laterPay`,
        '@groupBy': `entity.laterPay`
      }}).then((res) => {
        console.log('orderLaterPay', res.data)
        for (const i of res.data) {
          let earns = 0
          let actualEarns = 0
          if (i.laterPay === false) {
            earns += parseFloat(i.amount)
            actualEarns += parseFloat(i.amount)
          } else {
            earns += parseFloat(i.amount)
          }
          this.balance.earns = earns.toFixed(2)
          this.balance.actualEarns = actualEarns.toFixed(2)
        }
      })
      this.axios.get(`/officer/orders/statistics`, { params: {
        '@filter': `entity.getCreatedTime() >= datetime.get('${this.search.date[0]} 08:00:00') && entity.getCreatedTime() <= datetime.get('${endDate} 07:59:59')`
      }}).then((res) => {
        const list = []
        if (res.data.staff && res.data.staff.length > 1) {
          const data = []
          const ids = []
          for (const i of res.data.staff) {
            const index = ids.indexOf(i.id)
            if (index == -1) {
              ids.push(i.id)
              data.push({
                id: i.id,
                name: i.name,
                totalAmount: parseFloat(i.price),
                products: [
                  {
                    productName: i.productName,
                    quantity: i.quantity,
                    price: i.price
                  }
                ]
              })
            } else {
              data[index].products.push({
                productName: i.productName,
                quantity: i.quantity,
                price: i.price
              })
              data[index].totalAmount += parseFloat(i.price)
            }
          }
          res.data.staff = data
          res.data.staff.sort(function(a, b) {
            return b.totalAmount - a.totalAmount
          })
          list.push({
            name: '按销售员',
            type: 'staff'
          })
        }
        if (res.data.counter && res.data.counter.length > 1) {
          res.data.counter.sort(function(a, b) {
            return b.amount - a.amount
          })
          list.push({
            name: '按台号',
            type: 'counter'
          })
        }
        if (res.data.booking && res.data.booking.length > 1) {
          const data = []
          const ids = []
          for (const i of res.data.booking) {
            if (i.id == null) {
              i.id = 0
              i.name = '无订台人'
            }
            const index = ids.indexOf(i.id)
            if (index == -1) {
              ids.push(i.id)
              data.push({
                id: i.id,
                name: i.name,
                totalAmount: parseFloat(i.price),
                products: [
                  {
                    productName: i.productName,
                    quantity: i.quantity,
                    price: i.price
                  }
                ]
              })
            } else {
              data[index].products.push({
                productName: i.productName,
                quantity: i.quantity,
                price: i.price
              })
              data[index].totalAmount += parseFloat(i.price)
            }
          }
          res.data.booking = data
          res.data.booking.sort(function(a, b) {
            return b.totalAmount - a.totalAmount
          })
          list.push({
            name: '按订台人',
            type: 'booking'
          })
        }
        if (res.data.product && res.data.product.length > 1) {
          res.data.product.sort(function(a, b) {
            return b.totalPrice - a.totalPrice
          })
          list.push({
            name: '按产品',
            type: 'product'
          })
        }
        if (res.data.squad && res.data.squad.length > 1) {
          const data = []
          const ids = []
          for (const i of res.data.squad) {
            const index = ids.indexOf(i.id)
            if (index == -1) {
              ids.push(i.id)
              data.push({
                id: i.id,
                name: i.name,
                totalAmount: parseFloat(i.price),
                products: [
                  {
                    productName: i.productName,
                    quantity: i.quantity,
                    price: i.price
                  }
                ]
              })
            } else {
              data[index].products.push({
                productName: i.productName,
                quantity: i.quantity,
                price: i.price
              })
              data[index].totalAmount += parseFloat(i.price)
            }
          }
          res.data.squad = data
          res.data.squad.sort(function(a, b) {
            return b.totalAmount - a.totalAmount
          })
          list.push({
            name: '按小组',
            type: 'squad'
          })
        }
        if (res.data.team && res.data.team.length > 1) {
          const data = []
          const ids = []
          for (const i of res.data.team) {
            const index = ids.indexOf(i.id)
            if (index == -1) {
              ids.push(i.id)
              data.push({
                id: i.id,
                name: i.name,
                totalAmount: parseFloat(i.price),
                products: [
                  {
                    productName: i.productName,
                    quantity: i.quantity,
                    price: i.price
                  }
                ]
              })
            } else {
              data[index].products.push({
                productName: i.productName,
                quantity: i.quantity,
                price: i.price
              })
              data[index].totalAmount += parseFloat(i.price)
            }
          }
          res.data.team = data
          res.data.team.sort(function(a, b) {
            return b.totalAmount - a.totalAmount
          })
          list.push({
            name: '按团队',
            type: 'team'
          })
        }
        this.statistics = res.data
        if (list.length > 0) {
          this.activeName = list[0].type
        }
        this.list = list
        console.log('caidan', this.list, this.statistics)
      })
    },
    printTable() {
      print({
        printable: 'print',
        type: 'html',
        targetStyles: ['*']
      })
    },
    showOrderItem(data, index) {
      if (data) {
        console.log(data)
        this.productDialog.title = data.name + '(' + data.id + ')'
        this.getOrderItems(data.id, data.products[index].id)
      }
      this.productDialog.visible = true
    },
    getOrderItems(staffId, productId) {
      this.productDialog.items = []
      this.productDialog.loading = true
      this.axios.get(`/officer/order-items`, { params: {
        '@filter': `entity.getSpecification().getProduct().getId() == ${productId}
                 && entity.getOrder().getStaff().getId() == ${staffId}
                 && entity.getOrder().getStatus() >= 2 
                 && entity.getCreatedTime() >= datetime.get('${this.search.date[0]} ${this.checkDate}:00')
                 && entity.getCreatedTime() < datetime.get('${this.search.date[1]} ${this.checkDate}:00')`,
        '@expands': '["entity.order"]',
        limit: 10000000
      }})
        .then(res => {
          console.log('orderitem', res.data)
          this.productDialog.items = res.data
        })
        .finally(() => { this.productDialog.loading = false })
    },
    unSettle() {
      const loading = this.$loading({
        lock: true,
        text: '订单获取中',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      })
      const url = `/officer/orders`
      this.axios.get(url, {
        params: {
          '@filter': `entity.getStatus() == 4 && entity.getCreatedTime() >= datetime.get('${this.search.date[0]} ${this.checkDate}:00') && entity.getCreatedTime() < datetime.get('${this.search.date[1]} ${this.checkDate}:00')`,
          '@display': `{
              'id': 'entity.getId()'
          }`,
          limit: 10000000
        }})
        .then(async res => {
          if (res.data.length > 0) {
            for (var i of res.data) {
              try {
                await this.axios.post(`${url}/${i.id}/settle-remove`)
              } catch (e) {
                this.$message.error(`id:${i.id}订单结算失败！`)
              }
            }
            loading.close()
            this.$message.success('反结算成功！')
          } else {
            loading.close()
            this.$message.warning('暂无可反结算订单！')
          }
        }).catch(() => {
          loading.close()
        })
    },
    settleAll() {
      const loading = this.$loading({
        lock: true,
        text: '订单获取中',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      })
      const url = `/officer/orders`
      this.axios.get(url, {
        params: {
          '@filter': `(entity.getStatus() == 2 || entity.getStatus() == 3) && entity.getLaterPay() == 0`,
          '@display': `{
              'id': 'entity.getId()'
          }`,
          limit: 10000000
        }})
        .then(async res => {
          if (res.data.length > 0) {
            for (var i of res.data) {
              try {
                await this.axios.post(`${url}/${i.id}/settle-generate`)
              } catch (e) {
                this.$message.error(`id:${i.id}订单结算失败！`)
              }
            }
            loading.close()
            this.$message.success('结算成功！')
          } else {
            loading.close()
            this.$message.warning('暂无可结算订单！')
          }
        }).catch(() => {
          loading.close()
        })
    },
    showStaffs() {
      if (this.search.squad) {
        this.showStaffProductStatistics = this.staffProductStatistics.filter(v => v.squad === this.search.squad)
      } else {
        this.showStaffProductStatistics = this.staffProductStatistics
      }
    },
    filterGenerate() {
      const nextDate = new Date(new Date(this.search.date[1]).getTime() + 86400000)
      const endDate = `${nextDate.getFullYear()}/${nextDate.getMonth() + 1}/${nextDate.getDate()}`
      // this.search.date[1] = endDate
      console.log(this.search.date)
      this.filter = {
        after: `${endDate} 08:00:00`,
        before: `${this.search.date[1]} 07:59:59`
      }
      this.getStatistics()
    },
    // dataProcessor() {
    //   this.loading = true
    //   const promise = []

    //   // table数据
    //   promise.push(
    //     // 台号营收
    //     this.axios.get(`/officer/counters/statistics`, { params: Object.assign({
    //       '@filter': `entity.getEnabled() == true`,
    //       '@order': `entity.listOrder|ASC`
    //     }, this.filter) }).then(res => {
    //       const counters = []
    //       for (var i of res.data) {
    //         const item = i.entity
    //         item.amount = parseFloat(i.amount)
    //         counters.push(item)
    //       }
    //       counters.sort((a, b) => {
    //         return b.amount - a.amount
    //       })
    //       this.counters = counters
    //     })
    //   )
    //   promise.push(
    //     this.axios.get(`/officer/stores/statistics`, { params: this.filter }).then((res) => {
    //       this.storeStatistics = res.data
    //     })
    //   )
    //   promise.push(
    //     this.axios.get(`/officer/staffs`, { params: {
    //       '@expands': `["entity.collector"]`,
    //       'limit': 100000000
    //     }}).then(res => { this.staffs = res.data })
    //   )
    //   promise.push(
    //     this.axios.get(`/officer/squads`, { params: {
    //       'limit': 100000000
    //     }}).then(res => { this.squads = res.data })
    //   )
    //   Promise.all(promise).then(res => {
    //     this.loading = false
    //     if (this.storeStatistics) {
    //       this.balance.earns = this.storeStatistics.earns
    //       this.balance.actualEarns = this.storeStatistics.actualEarns
    //       // 产品销量
    //       if (this.storeStatistics.products) {
    //         const products = this.storeStatistics.products
    //         products.sort((a, b) => {
    //           if (a.productCategoryId !== b.productCategoryId) {
    //             return a.productCategoryId - b.productCategoryId
    //           } else {
    //             return b.quantity.localeCompare(a.quantity)
    //           }
    //         })
    //         this.products = products
    //       } else {
    //         this.products = []
    //       }
    //       // 人员销量
    //       if (this.storeStatistics.staffProductStatistics) {
    //         const data = this.storeStatistics.staffProductStatistics
    //         const array = []
    //         for (var datum of data) {
    //           const staff = this.staffs.find(v => v.id === datum.id)
    //           if (Object.keys(array).includes(String(datum['id']))) {
    //             array[datum['id']]['products'].push({ id: datum['productId'], name: datum['product'] + ' X ' + datum['quantity'] })
    //             array[datum['id']]['productAmounts'].push(datum['amount'])
    //             array[datum['id']]['amount'] += parseFloat(datum['amount'])
    //           } else {
    //             array[datum['id']] = {
    //               id: datum['id'],
    //               products: [{ id: datum['productId'], name: datum['product'] + ' X ' + datum['quantity'] }],
    //               productAmounts: [datum['amount']],
    //               amount: parseFloat(datum['amount']),
    //               name: datum['name'],
    //               squad: staff && staff.squad ? staff.squad.id : 0
    //             }
    //           }
    //         }
    //         const staffProductStatistics = []
    //         for (var i of Object.keys(array)) {
    //           staffProductStatistics.push(array[i])
    //         }
    //         staffProductStatistics.sort((a, b) => {
    //           return b.amount - a.amount
    //         })
    //         console.log(staffProductStatistics)
    //         this.staffProductStatistics = staffProductStatistics
    //       } else {
    //         this.staffProductStatistics = []
    //       }
    //     } else {
    //       this.balance.earns = 0
    //       this.products = []
    //       this.staffProductStatistics = []
    //     }
    //     this.showStaffs()
    //   })
    // },
    getProductSum(param) {
      const { columns, data } = param
      const sums = []

      columns.forEach((column, index) => {
        if (index === 0) {
          sums[index] = '总计'
          return
        }
        const values = data.map(item => Number(item[column.property]))
        if (index === 2 || index === 3) {
          sums[index] = values.reduce((prev, curr) => {
            const value = Number(curr)
            if (!isNaN(value)) {
              return prev + curr
            } else {
              return prev
            }
          }, 0).toFixed(2)
          // sums[index] += ' 元'
        } else {
          sums[index] = ''
        }
      })
      return sums
    },
    getCounterSum(param) {
      const { columns, data } = param
      const sums = []

      columns.forEach((column, index) => {
        if (index === 0) {
          sums[index] = '总计'
          return
        }
        const values = data.map(item => Number(item[column.property]))
        if (index === 2 || index === 3) {
          sums[index] = values.reduce((prev, curr) => {
            const value = Number(curr)
            if (!isNaN(value)) {
              return prev + curr
            } else {
              return prev
            }
          }, 0).toFixed(2)
          // sums[index] += ' 元'
        } else {
          sums[index] = ''
        }
      })
      return sums
    },
    getStaffSum(param) {
      const { columns, data } = param
      const sums = []

      columns.forEach((column, index) => {
        if (index === 0) {
          sums[index] = '总计'
          return
        }
        const values = data.map(item => Number(item[column.property]))
        if (index === 4) {
          sums[index] = values.reduce((prev, curr) => {
            const value = Number(curr)
            if (!isNaN(value)) {
              return prev + curr
            } else {
              return prev
            }
          }, 0).toFixed(2)
          // sums[index] += ' 元'
        } else {
          sums[index] = ''
        }
      })
      return sums
    }
  }
}
</script>

<style lang="scss" scoped>
.background {
  background-color: #f0f0f0;
  padding: 15px 15px 15px 15px;
  border-radius: 10px;
}
.detail {
  background-color: white;
  padding: 20px;
  text-align: center;
}
.text {
  font-size: 24px;
  padding-top: 10px;
}
</style>
